﻿using HslCommunication.Profinet.Siemens;
using LabelPrint.Utils;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NGPrint
{
    public partial class MainForm : Form
    {
        private SiemensS7Net siemensS7;
        private SerialPort serialPort;

        /// <summary>
        /// 上次请求
        /// </summary>
        private bool LastRequest { get; set; }

        private string ip = ConfigurationManager.AppSettings["IP"];
        private string dbRequest = ConfigurationManager.AppSettings["Request"];
        private string dbResponse = ConfigurationManager.AppSettings["Response"];
        private string dbHeartResponse = ConfigurationManager.AppSettings["HeartResponse"];
        private string dbbarCode = ConfigurationManager.AppSettings["BarCode"];

        public MainForm()
        {
            InitializeComponent();
            this.Load += MainForm_Load;
            this.FormClosing += MainForm_FormClosing;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show("您确定要退出当前程序吗？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result != DialogResult.OK)
            {
                e.Cancel = true;
            }
            serialPort?.Dispose();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            StartPLC();
            //StartCom();
        }

        public void StartCom()
        {
            serialPort = new SerialPort("com4", 115200, Parity.None, 8, StopBits.One);
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.ReadTimeout = 1500;
            serialPort.WriteTimeout = 1500;
            serialPort.Open();
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);
            SerialPort serialPort = (SerialPort)sender;
            int bytesToRead = serialPort.BytesToRead;
            byte[] ReDatas = new byte[serialPort.BytesToRead];
            serialPort.Read(ReDatas, 0, bytesToRead);
            var data = Encoding.ASCII.GetString(ReDatas);
            if (data.Contains("?"))
            {
                return;
            }
            this.BeginInvoke(new Action(() =>
            {
                txt_barCode.Text = data;
            }));
            PrintLable(data);
        }

        /// <summary>
        /// 信号读取
        /// </summary>
        private void StartPLC()
        {
            Task.Run(() =>
            {
                Thread.Sleep(200);
                while (true)
                {
                    if (siemensS7 == null)
                    {
                        siemensS7 = new SiemensS7Net(SiemensPLCS.S1500);
                        siemensS7.IpAddress = ip;
                        siemensS7.Port = 102;
                        siemensS7.SetPersistentConnection();
                        siemensS7.ConnectTimeOut = 2000;
                    }
                    try
                    {
                        //心跳信号
                        siemensS7.Write(dbHeartResponse, (short)(DateTime.Now.Second % 2));

                        var request = siemensS7.ReadBool(dbRequest).Content;
                        if (request != LastRequest && request == true)
                        {
                            LastRequest = request;
                            string barCode = siemensS7.ReadString(dbbarCode).Content;
                            this.BeginInvoke(new Action(() =>
                            {
                                txt_barCode.Text = barCode;
                            }));
                            PrintLable(barCode);
                            siemensS7.Write(dbResponse, (short)1);
                        }
                        if (request == false && LastRequest)
                        {
                            LastRequest = false;
                            siemensS7.Write(dbResponse, (short)0);
                        }
                    }
                    catch
                    {
                    }
                    Thread.Sleep(300);
                }
            });
        }

        private void PrintLable(string barCode)
        {
            //string connectionString = "Server=localhost; Port=3306; Database=appdb_nanyang_four_line; Uid=root; Pwd=ROOT; Charset=utf8mb4;SslMode=none;Min pool size=1;";
            string connectionString = "Server=localhost; Port=3306; Database=appdb_nanyang_three_line; Uid=root; Pwd=ROOT; Charset=utf8mb4;SslMode=none;Min pool size=1;";
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();

                    // 参数化查询避免SQL注入
                    string selectSql = @"SELECT * FROM prd_rework_defect_record
                            WHERE ProductCode = @barCode AND CurrentStatus = 1";
                    List<long> idsToUpdate = new List<long>();

                    using (MySqlCommand selectCommand = new MySqlCommand(selectSql, connection))
                    {
                        selectCommand.Parameters.AddWithValue("@barCode", barCode);

                        using (MySqlDataReader reader = selectCommand.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                // 打印标签
                                PrintLable(
                                    "智能三线",
                                    reader["FristStationCode"].ToString(),
                                    reader["ProductCode"].ToString(),
                                    "1",
                                    reader["DefectCode"].ToString(),
                                    reader["DetectionDate"].ToString()
                                );
                                idsToUpdate.Add(reader.GetInt64("Id"));
                            }
                        } // DataReader 在此处关闭
                    }
                    // 执行更新操作
                    foreach (long id in idsToUpdate)
                    {
                        string updateSql = "UPDATE prd_rework_defect_record SET CurrentStatus = 2 WHERE id = @id";
                        using (MySqlCommand updateCommand = new MySqlCommand(updateSql, connection))
                        {
                            updateCommand.Parameters.AddWithValue("@id", id);
                            updateCommand.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录或处理异常
                MessageBox.Show($"发生错误：{ex.Message}");
            }
        }

        public void PrintLable(string lineCode, string stationCode, string productId, string pallet, string errorCode, string date)
        {
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            keyValuePairs.Add("Station", stationCode);//工站
            keyValuePairs.Add("SN", productId);//SN码
            keyValuePairs.Add("Line", lineCode);//产线编号
            keyValuePairs.Add("Pallet", pallet);//托盘号
            keyValuePairs.Add("Alarmcode", "013");//故障代码
            keyValuePairs.Add("Date", date);//日期
            ZebraPrinter zebraPrinter = new ZebraPrinter("ErrorPrint");
            try
            {
                zebraPrinter.PrintAction("D:\\KS_MES2.0\\App\\Print\\PrintNG.btw", keyValuePairs);
            }
            catch
            {
                throw;
            }
        }
    }
}